package com.bankcomm.ui.views;

import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bankcomm.bean.ItemObject;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BOCMainHome;
import com.bankcomm.util.PinyinUtils;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

/**
 * 交行首页数据类，处理包括实时更新数据和离线更新数据
 * 
 * @author cheng.l 2013-5-28 下午08:19:11
 */
public class DataStorage {
	/**
	 * 登陆状态，true-已登陆，false-未登录
	 */
	public boolean isLogin = false;
	public String loginMessage = null;
	/**
	 * 实时更新的数据
	 * */
	public JSONObject updateJSON = null;
	/**
	 * 离线更新的数据
	 * */
	public JSONObject offlineJSON = null;

	/**
	 * 频道标题
	 * */
	public int remommendSize = 0;
	public String[] mTitles = {};
	/**
	 * 由上到下，从左到右，依次是
	 * 
	 * 我的首页、强推频道、用户列表、生活服务、金融 服务、投资理财、左侧设置
	 * */
	public ArrayList<Map<String, Object>> array1 = new ArrayList<Map<String, Object>>();
	public ArrayList<Map<String, Object>> recommendList, userList, array2,
			array3, array4, settings;

	/**
	 * 推送、消息和优惠快讯列表
	 */
	public ArrayList<Map<String, Object>> pushNews, myNews, favNews;

	/**
	 * 广告列表
	 */
	public ArrayList<Map<String, Object>> adList = new ArrayList<Map<String, Object>>();

	/**
	 * 首頁城市、省市
	 */
	public ArrayList<ItemObject> lists = new ArrayList<ItemObject>();
	/**
	 * 热门城市
	 */
	public ArrayList<ItemObject> hotlists = new ArrayList<ItemObject>();
	/**
	 * 登陆证件类型和名字
	 */
	public String[] certTypes = {};
	public String[] certNames = {};
	/**
	 * 登陆URL
	 * */
	public String loginURL = "";
	public String registURL = "";
	/**
	 * 同步九宫格到服务器的URL
	 */
	public String uploadURL = "";

	public Context context;
	/*
	 * 消息盒子上未读消息的条数
	 */
	public String unreadnewscount = "";

	public DataStorage(Context context, String reply) {
		this.context = context;
		initOfflineJson();
		initUpdateJson(reply);
	}

	/**
	 * 解析首页代码，可能存在离线文件或者存到本地的
	 */
	private void initMyHome(JSONObject offline) {
		// TODO Auto-generated method stub
		// 交行推荐的首页内容
		recommendList = new ArrayList<Map<String, Object>>();
		userList = new ArrayList<Map<String, Object>>();
		recommendList.clear();
		userList.clear();
		array1.clear();
		try {
			// 用户自定义的首页内容
			JSONArray user = null;
			String json = PackageManagerAndroid.ANDROIDDB.get("UserList");
			if (null != json && !"".equalsIgnoreCase(json)) {
				user = new JSONObject(json).getJSONArray("user");
			}
			if (null == user || user.length() <= 0) {
				//取得保存本地的文件
				if(null == user || user.length() <= 0){
					String temp = PackageManagerAndroid.ANDROIDDB.get("TempHomeList");
					if(null != temp && !"".equalsIgnoreCase(temp)){
						user = new JSONArray(temp);						
					}
				}
				if (null != offline && (user == null || user.length() <= 0 )) {
					user = offline.getJSONArray("my_favorite");
					if(null != user){
						PackageManagerAndroid.ANDROIDDB.save("TempHomeList", user.toString());
					}
				}
				
			}
			userList = parseChannelJson(user);
			if (null != recommendList) {
				remommendSize = recommendList.size();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		array1.clear();
		array1.addAll(0, userList);
		array1.addAll(0, recommendList);
		Map<String, Object> end = new HashMap<String, Object>();
		end.put("id", "menuitem_add");
		end.put("name", "添加应用");
		array1.add(end);
	}

	/**
	 * 初始化从后台实时更新的数据
	 * 
	 * @param update
	 */
	public void initUpdateJson(String update) {
		if (null == update || "".equalsIgnoreCase(update)) {
			return;
		}
		try {
			updateJSON = new JSONObject(update);
			uploadURL = updateJSON.getString("menuUp");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		parseAdvertisement();
		parseNewsMessage();
		if (null != updateJSON) {
			try {
				JSONObject obj = updateJSON.getJSONObject("ebankMenu");
				if (null != obj) {
					parseMyHomeChannel(obj);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 初始化离线offlineJson数据
	 */
	public void initOfflineJson() {
		try {
			// 取得离线更新文件的名字
			String fileName = null;
			if (null != updateJSON) {
				fileName = updateJSON.getString("offlineFile");
			} else {
				fileName = "mainPage.json";
			}

			if (null != fileName) {
				String temp = Utils.getFileFromOffline(fileName);
				Utils.printOutToConsole("------offline------"+temp);
				offlineJSON = new JSONObject(temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		parseOthersChannel();
		parseCertTypeNames();
		parseSettings();
		initSearchTypeData();
		initMyHome(offlineJSON);
		// 判断是大学生版本还是普通版本
		String version = LPMid.getInstance().read("version");
		if (null != version && version.equalsIgnoreCase("university")) {
			readProvince();
		} else {
			parseCitys();
		}

		// 增加天气预报
		Map<String, Object> weatherMap = new HashMap<String, Object>();
		weatherMap.put("imageURL", "weather");
		weatherMap.put("contentURL", "weather");
		if (!adList.contains(weatherMap)) {
			adList.add(0, weatherMap);
		}
		mTitles[0] = "我的首页";
	}


	/**
	 * 加密信道建立完成后刷新offlineJson数据
	 */
	public void initOfflineJsonTwo() {
		try {
			// 取得离线更新文件的名字
			String fileName = null;
			if (null != updateJSON) {
				fileName = updateJSON.getString("offlineFile");
			} else {
				fileName = "mainPage.json";
			}

			if (null != fileName) {
				String temp = Utils.getFileFromOffline(fileName);
				Utils.printOutToConsole("------offline2------"+temp);
				offlineJSON = new JSONObject(temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		parseOthersChannel();
		parseCertTypeNames();
		parseSettings();
		initSearchTypeData();
		// 判断是大学生版本还是普通版本
		String version = LPMid.getInstance().read("version");
		if (null != version && version.equalsIgnoreCase("university")) {
			readProvince();
		} else {
			parseCitys();
		}

		// 增加天气预报
		Map<String, Object> weatherMap = new HashMap<String, Object>();
		weatherMap.put("imageURL", "weather");
		weatherMap.put("contentURL", "weather");
		if (!adList.contains(weatherMap)) {
			adList.add(0, weatherMap);
		}
		mTitles[0] = "我的首页";
	}

	/**
	 * 重新登陆后要重置我的首页
	 */
	public void resetMyHome() {
		if (null != updateJSON) {
			try {
				array1.clear();
				recommendList.clear();
				userList.clear();
				JSONObject obj = updateJSON.getJSONObject("ebankMenu");
				if (null != obj) {
					parseMyHomeChannel(obj);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 初始化"我的首页"频道数据，实时更新
	 */
	private void parseMyHomeChannel(JSONObject homeObject) {
		// TODO Auto-generated method stub
		try {
			if (null != recommendList) {
				recommendList.clear();
			}
			if (null != userList) {
				userList.clear();
			}

			mTitles[0] = homeObject.getString("name");

			// 交行推荐的首页内容
			JSONArray recommend = homeObject.getJSONArray("recommend");
			recommendList = parseChannelJson(recommend);

			// 用户自定义的首页内容
			JSONArray user = null;
			String json = PackageManagerAndroid.ANDROIDDB.get("UserList");
			if (null != json && !"".equalsIgnoreCase(json)) {
				user = new JSONObject(json).getJSONArray("user");
			} else {
				user = homeObject.getJSONArray("user");
			}
			userList = parseChannelJson(user);

			if (null != recommendList) {
				remommendSize = recommendList.size();
			}
			array1.clear();
			array1.addAll(0, userList);
			array1.addAll(0, recommendList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		/**
		 * 我的首页--中"添加"item
		 * */
		Map<String, Object> end = new HashMap<String, Object>();
		end.put("id", "menuitem_add");
		end.put("name", "添加应用");
		array1.add(end);
	}

	/**
	 * 初始化其他的频道数据,从离线文件中读取
	 */
	private void parseOthersChannel() {
		// TODO Auto-generated method stub
		try {
			if (null != offlineJSON) {
				JSONArray array = offlineJSON.getJSONArray("ebankMenu");
				if (null != array) {
					int size = array.length();
					mTitles = new String[size + 1];
					for (int i = 0; i < size; i++) {
						JSONObject item = array.getJSONObject(i);
						mTitles[i + 1] = item.getString("name");
						// 解析对应频道的内容
						JSONArray o = item.getJSONArray("channels");
						if (i == 0) {
							array2 = parseChannelJson(o);
						} else if (i == 1) {
							array3 = parseChannelJson(o);
						} else if (i == 2) {
							array4 = parseChannelJson(o);
						}
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 解析左侧设置相关
	 */
	private void parseSettings() {
		if (null != offlineJSON) {
			try {
				JSONArray setObject = offlineJSON.getJSONArray("setting");
				if (null != setObject) {
					settings = parseChannelJson(setObject);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 解析九宫格中的频道
	 * 
	 * @param channel
	 * @return
	 */
	private ArrayList<Map<String, Object>> parseChannelJson(JSONArray array) {
		ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			if (null != array) {
				int size = array.length();
				for (int i = 0; i < size; i++) {
					JSONObject o = array.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					String name = o.getString("name");
					String url = o.getString("url");
					map.put("id", o.getString("id"));
					map.put("name", name == null ? "" : name);
					map.put("url", url == null ? "" : url);
					// 标记是否是新增频道
					String newId = null;
					try {
						newId = o.getString("user_id");
					} catch (Exception e) {
						// TODO: handle exception
					}
					if(newId!= null&&!newId.equals("")){
						map.put("user_id",newId);
					}else{
						newId = "undefined";
						map.put("user_id",newId);
					}
					list.add(map);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 解析登陆时的证件类型和证件名字
	 */
	private void parseCertTypeNames() {
		// TODO Auto-generated method stub
		try {
			if (null != offlineJSON) {
				JSONObject objForm = offlineJSON.getJSONObject("form");
				if (null != objForm) {
					loginURL = objForm.getString("loginUrl");
					registURL = objForm.getString("registUrl");
					JSONArray certArray = objForm
							.getJSONArray("certificateType");
					if (null != certArray) {
						int length = certArray.length();
						certTypes = new String[length];
						certNames = new String[length];
						for (int i = 0; i < length; i++) {
							JSONObject item = certArray.getJSONObject(i);
							certNames[i] = item.getString("name");
							certTypes[i] = item.getString("value");

						}
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 解析广告图片数据
	 */
	private void parseAdvertisement() {
		if (null != updateJSON) {
			try {
				adList.clear();
				// 增加天气预报
				Map<String, Object> weatherMap = new HashMap<String, Object>();
				weatherMap.put("imageURL", "weather");
				weatherMap.put("contentURL", "weather");
				if (!adList.contains(weatherMap)) {
					adList.add(0, weatherMap);
				}
				JSONArray adArray = updateJSON.getJSONArray("ad");
				if (null != adArray) {
					int length = adArray.length();
					for (int i = 0; i < length; i++) {
						JSONObject o = adArray.getJSONObject(i);
						Map<String, Object> map = new HashMap<String, Object>();
						String imageURL = o.getString("img_url");
						String contentURL = o.getString("content_url");
						map.put("imageURL", imageURL == null ? "" : imageURL);
						map.put("contentURL", contentURL == null ? ""
								: contentURL);

						adList.add(map);
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 解析消息列表和优惠快讯，以及消息推送页面
	 */
	@SuppressWarnings({ "unchecked" })
	private void parseNewsMessage() {
		if (null != updateJSON) {
			try {
				JSONArray array = updateJSON.getJSONArray("pushNotices");
				if (null != array) {
					pushNews = pareseNews(array);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 消息盒子上未读消息
			try {
				unreadnewscount = updateJSON.getString("unreadCount");
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 解析消息列表
	 * 
	 * @param newsObj
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ArrayList pareseNews(JSONArray newsArray) {
		ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			int size = newsArray.length();
			for (int i = 0; i < size; i++) {
				JSONObject o = newsArray.getJSONObject(i);
				Map<String, Object> map = new HashMap<String, Object>();
				String title = o.getString("content");
				String url = o.getString("url");

				map.put("content", title == null ? "" : title);
				map.put("url", url == null ? "" : url);

				list.add(map);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/*
	 * 解析消息盒子返回的JSON数据
	 */
	@SuppressWarnings("unchecked")
	public void parsNewsReply(String reply) {
		JSONObject NEWSBOX = null;
		if (reply != null && !reply.equalsIgnoreCase("")) {
			try {
				NEWSBOX = new JSONObject(reply);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				JSONArray myNewsArray = NEWSBOX.getJSONArray("myNews");
				if (null != myNewsArray) {
					myNews = pareseNews(myNewsArray);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				JSONArray favNewsArray = NEWSBOX.getJSONArray("favNews");
				if (null != favNewsArray) {
					favNews = pareseNews(favNewsArray);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 解析首页的城市
	 */
	@SuppressWarnings("unchecked")
	public void parseCitys() {
		lists.clear();
		lists = null;
		lists = new ArrayList<ItemObject>();
		// 热门城市
		hotlists.clear();
		hotlists = null;
		hotlists = new ArrayList<ItemObject>();
		if (null != offlineJSON) {
			try {
				// 解析普通城市
				JSONArray mCitysArray = offlineJSON.getJSONArray("citys");
				if (null != mCitysArray) {
					int size = mCitysArray.length();
					for (int i = 0; i < size; i++) {
						JSONObject o = mCitysArray.getJSONObject(i);
						ItemObject item = new ItemObject();
						String code = o.getString("cityCode");
						String name = o.getString("cityName");
						String branch = o.getString("branchNo");
						item.code = null != code ? code : "";
						item.name = null != name ? name : "";
						item.branch = null != branch ? branch : "";
						lists.add(item);
					}
					// 对城市按首字母排序
					Collections.sort(lists, new MyComparator() {
					});
				}
				// 解析热门城市
				JSONArray hotCitysArray = offlineJSON.getJSONArray("hotcitys");
				if (null != hotCitysArray) {
					int size = hotCitysArray.length();
					for (int i = 0; i < size; i++) {
						JSONObject o = hotCitysArray.getJSONObject(i);
						ItemObject item = new ItemObject();
						String code = o.getString("cityCode");
						String name = o.getString("cityName");
						String branch = o.getString("branchNo");
						item.code = null != code ? code : "";
						item.name = null != name ? name : "";
						item.branch = null != branch ? branch : "";
						hotlists.add(item);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 读取省份
	 */
	public void readProvince() {
		lists.clear();
		lists = null;
		lists = new ArrayList<ItemObject>();
		SQLiteDatabase db = LPMid.getInstance().db;
		Cursor cursorProvince = null;
		try {
			// 读取省份
			String queryProvince = "select * from " + DBManager.TABLE_PROVINCE;
			cursorProvince = db.rawQuery(queryProvince, null);
			while (cursorProvince.moveToNext()) {
				ItemObject ip = new ItemObject();

				ip.name = cursorProvince.getString(cursorProvince
						.getColumnIndex(DBManager.TABLE_PROVINCE_COLUMN_NAME));
				ip.provinceID = cursorProvince.getInt(cursorProvince
						.getColumnIndex(DBManager.TABLE_PROVINCE_COLUMN_ID));
				ip.provinceShortKey = PinyinUtils.String2Alpha(ip.name);

				lists.add(ip);
				// Utils.printOutToConsole(ip.provinceID+"--"+ip.name+"--"+ip.provinceShortKey);
			}
			// Collections.sort(lists, new MyComparator(){});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据省份读取学校
	 * 
	 * @param province
	 */
	public ArrayList<ItemObject> readUniversity(int provinceID) {
		ArrayList<ItemObject> temp = new ArrayList<ItemObject>();
		SQLiteDatabase db = LPMid.getInstance().db;
		Cursor cursorCollege = null;
		try {
			// 读取省份
			String queryProvince = "select * from " + DBManager.TABLE_COLLEGE
					+ " where " + DBManager.TABLE_COLLEGE_COLUMN_PROVINCE_ID
					+ "=?";
			cursorCollege = db.rawQuery(queryProvince,
					new String[] { String.valueOf(provinceID) });
			if (null != cursorCollege && cursorCollege.getCount() > 0) {
				while (cursorCollege.moveToNext()) {
					ItemObject io = new ItemObject();
					io.name = cursorCollege
							.getString(cursorCollege
									.getColumnIndex(DBManager.TABLE_COLLEGE_COLUMN_NAME));
					io.universityId = cursorCollege.getInt(cursorCollege
							.getColumnIndex(DBManager.TABLE_COLLEGE_COLUMN_ID));
					io.universityType = cursorCollege
							.getInt(cursorCollege
									.getColumnIndex(DBManager.TABLE_COLLEGE_COLUMN_TYPE));

					// Utils.printOutToConsole(io.universityId+"--"+io.universityType+"--"+io.name);
					temp.add(io);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return temp;
	}

	/**
	 * 排序方法
	 */
	@SuppressWarnings("rawtypes")
	public class MyComparator implements Comparator {

		private Collator collator = Collator.getInstance();

		public MyComparator() {

		}

		@Override
		public int compare(Object object1, Object object2) {
			// TODO Auto-generated method stub
			CollationKey key1 = collator.getCollationKey(PinyinUtils
					.getFirtChar(((ItemObject) object1).name));
			CollationKey key2 = collator.getCollationKey(PinyinUtils
					.getFirtChar(((ItemObject) object2).name));
			return key1.compareTo(key2);
		}
	}

	/**
	 * 初始化周边搜索分类数据
	 */
	private void initSearchTypeData() {
		LPMid.getInstance().bigMap = new HashMap<Integer, String>(); // 大类数据
		LPMid.getInstance().smallMap = new HashMap<Integer, HashMap<Integer, String>>(); // 小类数据
		if (null != offlineJSON) {
			try {
				JSONArray jsonArray = offlineJSON.getJSONArray("searchType");
				if (null != jsonArray && jsonArray.length() > 0) {
					LPMid.getInstance().bigClass = new String[jsonArray
							.length()];
					LPMid.getInstance().smallClass = new String[jsonArray
							.length()][];
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = new JSONObject(
								jsonArray.getString(i));
						String key = jsonObject.keys().next().toString();
						LPMid.getInstance().bigClass[i] = key;
						Object value = jsonObject.get(key);
						if (value instanceof JSONArray) {
							String[] valueCity = null;
							JSONArray valueJson = new JSONArray(
									value.toString());
							if (valueJson.length() > 0) {
								valueCity = new String[valueJson.length()];
								HashMap<Integer, String> cityMap = new HashMap<Integer, String>();
								for (int j = 0; j < valueJson.length(); j++) {
									JSONObject valJsonObject = new JSONObject(
											valueJson.getString(j));
									String valKey = valJsonObject.keys().next()
											.toString();
									valueCity[j] = valKey;

									// 小类
									cityMap.put(j, valJsonObject.get(valKey)
											.toString());
								}
								LPMid.getInstance().smallMap.put(i, cityMap);
								LPMid.getInstance().smallClass[i] = valueCity;
							}
						} else {
							// 大类
							LPMid.getInstance().bigMap.put(i, value.toString());
							LPMid.getInstance().smallClass[i] = new String[] {};
						}
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 判断是否进入消息推送页面
	 * 
	 * @return
	 */
	public boolean stepIntoPushMessage() {
		String pushMessage = PackageManagerAndroid.ANDROIDDB.get("pushMessage");
		if (pushMessage.equalsIgnoreCase("true")) {
			return true;
		}
		return false;
		// if(null != pushNews && pushNews.size() > 0){
		// return true;
		// }else{
		// return false;
		// }
	}

	/**
	 * 解析登陆后返回的报文
	 * 
	 * @return
	 */
	public void parseLoginMessage(String reply) throws Exception {
		JSONObject obj = new JSONObject(reply);
		if (null != obj) {
			JSONObject paramsObj = obj.getJSONObject("loginParams");
			if (null != paramsObj) {
				String status = paramsObj.getString("clientStatus");
				String bankUserCode = paramsObj.getString("bankUserCode");
				if (null != status && status.equalsIgnoreCase("1") && null != bankUserCode && !"".equalsIgnoreCase(bankUserCode)) {
					isLogin = true;
					// 保存UserCode
					LPMid.getInstance().um_.saveBankUserCode(paramsObj
							.getString("bankUserCode"));
					try {
						((Activity) context).runOnUiThread(new Runnable() {
							@Override
							public void run() {
								BOCMainHome.bcmHomeView.changeExit();
							}
						});
						// userName checkInfo logonTimes lastLogon
						loginMessage = paramsObj.getString("checkInfo");
						loginMessage = null == loginMessage ? "" : loginMessage;
					} catch (Exception e) {
						e.printStackTrace();
					}

					try {
						/**
						 * 首次登陆后，返回用户的"我的首页"并刷新
						 */
						JSONObject favObj = obj.getJSONObject("ebankMenu");
						if (null != favObj) {
							array1.clear();
							parseMyHomeChannel(favObj);
							((Activity) context).runOnUiThread(new Runnable() {
								@Override
								public void run() {
									BOCMainHome.bcmHomeView.resetMyFavorite();
								}
							});
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 保存用户列表到本地
	 * 
	 * @param list
	 */
	public void saveToLocal(ArrayList<Map<String, Object>> homeList) {

		ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(
				homeList);
		String channels = "";
		if (null != recommendList && recommendList.size() > 0) {
			list.removeAll(recommendList);
		}

		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				continue;
			}
			Map<String, Object> item = list.get(i);
			String shortCut = item.get("id").toString();
			String name = "";
			if (null != item.get("name")) {
				name = item.get("name").toString();
			}
			String url = "";
			if (null != item.get("url")) {
				url = item.get("url").toString();
			}

			channels = channels.concat("{'id':" + "'" + shortCut + "',"
					+ "'name':" + "'" + name + "'," + "'url':" + "'" + url
					+ "'},");
		}
		String json = "";
		if (!"".equalsIgnoreCase(channels)) {
			json = "{'user':[" + channels.substring(0, channels.length() - 1)
					+ "]}";
		}
		PackageManagerAndroid.ANDROIDDB.save("UserList", json);
		list.clear();
		list = null;
	}

	/**
	 * 如果该频道含有新增的标记，若用户点击了，将不显示"新增的标记"
	 * 
	 * @param newChannel
	 *            add by cl 2013.10.24
	 */
	public void saveClickedNewChannel(String channelID) {
		if (null == channelID || "".equalsIgnoreCase(channelID)) {
			return;
		}
		String channels = "";
		String saved = PackageManagerAndroid.ANDROIDDB.get("NewChannelList");
		if (null != saved && !"".equalsIgnoreCase(saved)) {
			channels = saved + "," + channelID;
		} else {
			channels = channelID;
		}
		PackageManagerAndroid.ANDROIDDB.save("NewChannelList", channels);
	}

	/**
	 * 判断是否已经保存用户已点过的新增图标
	 * 
	 * @param id
	 * @return add by cl 2013.10.24
	 */
	public boolean isSavedChannelId(String channelID) {
		if (null == channelID || "".equalsIgnoreCase(channelID)) {
			return false;
		}
		String saved = PackageManagerAndroid.ANDROIDDB.get("NewChannelList");
		if (null != saved && !"".equalsIgnoreCase(saved)) {
			String[] channels = saved.split(",");
			if (null != channels) {
				int length = channels.length;
				for (int i = 0; i < length; i++) {
					if (channels[i].equalsIgnoreCase(channelID)) {
						return true;
					}
				}
			}
		} else {
			return false;
		}
		return false;
	}

	/**
	 * 登陆超时后，重建加密信道，重置登陆信息
	 */
	public void resetLoginInfo() {
		LPToastUtil.isBuildChannel = true;
		Utils.keyDlg_ = null;
		// 登陆状态
		isLogin = false;
		// 登陆信息
		loginMessage = "";
		// 重置我的首页
		resetMyHome();
		// 编辑状态
		DropGridAdapter.isInEdit = false;
	}

	public void release() {
		// TODO Auto-generated method stub
		isLogin = false;
		certTypes = null;
		certNames = null;
		loginURL = null;
		updateJSON = null;
		offlineJSON = null;
		mTitles = null;
		if (null != array1) {
			array1.clear();
			array1 = null;
		}
		if (null != array1) {
			array1.clear();
			array1 = null;
		}
		if (null != array2) {
			array2.clear();
			array2 = null;
		}
		if (null != array3) {
			array3.clear();
			array3 = null;
		}
		if (null != array4) {
			array4.clear();
			array4 = null;
		}
		if (null != settings) {
			settings.clear();
			settings = null;
		}
		if (null != adList) {
			adList.clear();
			adList = null;
		}
		if (null != myNews) {
			myNews.clear();
			myNews = null;
		}
		if (null != favNews) {
			favNews.clear();
			favNews = null;
		}
		if (null != lists) {
			lists.clear();
			lists = null;
		}
		if (null != pushNews) {
			pushNews.clear();
			pushNews = null;
		}
	}
}
